<?php

namespace app\api\controller;


use app\api\model\ChickenCards;
use app\api\model\AdminConfigs as AdminConfigsDB;

use app\traits\CommonScript;
use app\traits\OpChickenCard;
use Illuminate\Support\Carbon;
use support\Request;
use Tinywan\Jwt\JwtToken;

//更新数据库
use app\api\model\cards as CardsDB;
use app\api\model\GameCar as GameCarDB;
use app\api\model\Eggs as EggsDB;
use app\api\model\Game2 as Game2DB;
use app\api\model\Game2Players as Game2PlayersDB;
use app\api\model\Game2PlayersSum as Game2PlayersSumDB;
use app\api\model\GameBowl as GameBowlDB;
use app\api\model\GameBowlPlayers as GameBowlPlayersDB;
use app\api\model\GameCarsPlayer as GameCarsPlayerDB;
use app\api\model\GiftEggs as GiftEggsDB;
use app\api\model\InviteRecord as InviteRecordDB;
use app\api\model\ManualCards as ManualCardsDB;
use app\api\model\User;
use app\api\model\UserUseCards as UserUseCardsDB;
use app\api\model\Wallets;
use app\api\model\Yue as YueDB;
use app\api\model\SmsCode as SmsCodeDB;

use yzh52521\mailer\Mailer;

class UserController
{
    use OpChickenCard;
    use CommonScript;

    //清除数据
    public function test(Request $request)
    {
        $res = [];
        CardsDB::truncate();
        GameCarDB::truncate();
        EggsDB::truncate();
        Game2DB::truncate();
        Game2PlayersDB::truncate();
        Game2PlayersSumDB::truncate();
        GameBowlDB::truncate();
        GameBowlPlayersDB::truncate();
        GameCarsPlayerDB::truncate();
        GiftEggsDB::truncate();
        InviteRecordDB::truncate();
        ManualCardsDB::truncate();
        User::truncate();
        UserUseCardsDB::truncate();
        YueDB::truncate();
        Wallets::truncate();
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    public function test1(Request $request)
    {
        Mailer::setFrom('crazyhen2024@gmail.com')
            ->setTo('a304497570@gmail.com')
            ->setSubject('疯狂母鸡')
            ->setTextBody('您的验证码是:' . '1234,' . '有效期为5分钟')
            ->send();
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => 111,
        ]);
    }


    //U蛋调账
    public function eggsList(Request $request)
    {
        $uid = $request->uid;
        $type = $request->get('type');
        $res = EggsDB::where('uid', $uid)->where('type', 'like', '%' . $type . '%')->orderBy('id', 'desc')->paginate(10);
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    //卡片调账
    public function cardsList(Request $request)
    {
        $uid = $request->uid;
        $type = $request->get('type');
        $res = CardsDB::where('uid', $uid)->where('type', 'like', '%' . $type . '%')->orderBy('id', 'desc')->paginate(10);
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);

    }

    //余额调账
    public function yueList(Request $request)
    {
        $uid = $request->uid;
        $type = $request->get('type');
        $res = YueDB::where('uid', $uid)->where('type', 'like', '%' . $type . '%')->orderBy('id', 'desc')->paginate(10);
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);

    }


    /**
     * @param Request $request
     * @param User $DB
     * @return \support\Response
     * 邮箱发送验证码
     */
    public function sendCode(Request $request, User $DB)
    {

        $mail = $request->get('mail', '');
        //获取验证码 写入数据
        $code = '1234';
//        $code = $this->generateRandomCode();
        $res = SmsCodeDB::where('mail', $mail)->first();
        if ($res) {
            //获取当前时间
            $now_time = Carbon::now()->addMinutes(2);
            $last_at = Carbon::parse($res['last_at']);
            if ($now_time > $last_at) {
                SmsCodeDB::where('mail', $mail)->sharedLock()->update([
                    'code' => $code,
                    'last_at' => Carbon::now()->addMinutes(5)->toDateTimeString(),
                    'updated_at' => Carbon::now()->toDateTimeString()
                ]);
            }else{
                return json([
                    'code' => 0,
                    'msg' => '',
                    'data' => '请3分钟后再试。'
                ]);
            }
        } else {
            SmsCodeDB::insertGetId([
                'mail' => $mail,
                'code' => $code,
                'last_at' => Carbon::now()->addMinutes(5)->toDateTimeString(),
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
        }
        Mailer::setFrom('crazyhen2024@gmail.com')
            ->setTo($mail)
            ->setSubject('疯狂母鸡')
            ->setTextBody('您的验证码是:' . $code . '有效期为5分钟')
            ->send();
        return json([
            'code' => 2,
            'msg' => '发送成功',
            'data' => $code
        ]);

    }

    /**
     * @param Request $request
     * @param User $DB
     * @return \support\Response
     * 用户注册-验证码
     */
    public function register(Request $request, User $DB)
    {
        $mail = $request->post('mail', '');
        $code = $request->post('code', '');
        if ($code == '1234') {
            $res = $DB->where('mail', $mail)->first();
        } else {
            return json(['code' => 0, 'msg' => '验证码错误', 'data' => '',]);
        }
        if ($res) {
            return json([
                'code' => 4,
                'msg' => '邮箱已存在',
                'data' => ''
            ]);
        } else {
            return json([
                'code' => 2,
                'msg' => '验证成功，请继续注册',
                'data' => ''
            ]);
        }

    }

    /**
     * @param Request $request
     * @param User $DB
     * @return \support\Response
     * 用户注册-设置密码
     */
    public function registerTo(Request $request, User $DB, Wallets $wallets)
    {
        $mail = $request->post('mail', '');
        $code = $request->post('code', '');
        $invite_code = $request->post('invite_code', '');
        $login_password = $request->post('login_password', '');
        $trade_password = $request->post('trade_password', '');

        //查验邮箱
        $mail_info = $DB->where('mail', $mail)->first();
        if($mail_info){
            return json([
                'code' => 0,
                'msg' => '邮箱已注册!',
                'data' => ''
            ]);
        }

        //查询验证码
        $code_info = SmsCodeDB::where('mail', $mail)->first();
        if(!$code_info){
            return json([
                'code' => 0,
                'msg' => '验证码未知',
                'data' => ''
            ]);
        }

        if($code_info['code']!=$code){
            return json([
                'code' => 0,
                'msg' => '验证码错误',
                'data' => ''
            ]);
        }

        $uid = $this->generateId($mail);  //随机生成ID
        //获取上一级id
//            $parent_id = $DB->where('uid', $invite_code)->value('uid');
        $DB->insertGetId([
            'mail' => $mail,
            'uid' => $uid,
            'parent_id' => $invite_code,
            'login_password' => password_hash($login_password, PASSWORD_DEFAULT),
            'trade_password' => password_hash($trade_password, PASSWORD_DEFAULT),
            'created_at' => Carbon::now()->toDateTimeString(),
        ]);
//             钱包参数
//            (['user_id', 'green_card_1', 'green_card_2', 'green_card_3', 'green_card_4', 'green_card_5', 'blue_card_1', 'blue_card_2', 'gold_card_1',
//                'red_card_1','black_card_1','gold_card_album','red_card_album','black_card_album','held_eggs','producing_eggs','used_chickens','producing_chickens',
//                'created_at','updated_at']);
        $res = $wallets->insertGetId([
            'wallet_user_id' => $uid,
            'email' => $mail,
            'created_at' => Carbon::now()->toDateTimeString(),
        ]);
        //添加邀请记录
        if ($invite_code != '') {
            $add_eggs = AdminConfigsDB::where('id', 2)->value('reward_egg_count');
            InviteRecordDB::insertGetId([
                'user_id' => $invite_code,
                'invite_id' => $uid,
                'get_eggs' => $add_eggs,
                'is_exchange' => 2,
                'created_at' => Carbon::now()->toDateTimeString(),
            ]);
        }
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    /**
     * @param Request $request
     * @param User $DB
     * @return \support\Response
     * 用户登录
     */
    public function login(Request $request, User $DB)
    {
        $data = $request->only(['mail', 'login_password']);
        $ha_login_password = $DB->where('mail', $data['mail'])->value('login_password');
        $res = false;
        if (password_verify($data['login_password'], $ha_login_password)) {
            $res = $DB->where('mail', $data['mail'])
                ->select('uid', 'mail', 'login_password')
                ->first();
        }
        if ($res) {
            $data = $this->getToken($res);
            return json([
                'code' => 2,
                'msg' => '登录成功！',
                'data' => $data,
            ]);
        } else {
            return json([
                'code' => 4,
                'msg' => '账号或密码错误!',
                'data' => '',
            ]);
        }
    }

    /***
     * @param Request $request
     * @param User $DB
     * @return \support\Response
     * 获取用户信息
     */
    public function userInfo(Request $request, User $DB)
    {
        $uid = JwtToken::getCurrentId();
//        $res = $DB->where('uid', $uid)
//            ->join('wallets', 'user_logins.uid', '=', 'wallets.wallet_user_id')
//            ->select('user_logins.uid','user_logins.phone_number', 'user_logins.nickname','user_logins.avatar','user_logins.parent_id')
//            ->first();
        $res = $DB->where('uid', $uid)->select('uid', 'mail', 'nickname', 'avatar',
            'parent_id', 'is_auth')->first();
        return json([
            'code' => 2,
            'msg' => '成功',
            'data' => $res,
        ]);
    }

    public function getToken($res)
    {
        $data = [
            'id' => $res['uid'], // 这里必须是一个全局抽象唯一id
            'mail' => $res['mail'],
            'login_password' => $res['login_password'],
        ];
        $token = JwtToken::generateToken($data);
        return $token;
    }

    /**
     * 登出
     *
     */
    public function logout()
    {
        $res = JwtToken::clear();
        return json([
            'code' => 2,
            'msg' => '成功',
            'data' => $res,
        ]);
    }


    /***
     *
     * 修改用户密码
     */
    public function changePassword(Request $request, User $DB)
    {
        $pwd = $request->post('login_password');
        // 获取当前用户ID
        $uid = $request->uid;
        //二级安全码
        $id_auth = $DB->where('uid', $uid)->value('is_auth');
        if ($id_auth == 1) {
            $auth_password = $request->post('auth_password');
            $auth_password_db = $DB->where('uid', $uid)->value('auth_password');
            if (!$this->verifyTradePwd($auth_password, $auth_password_db)) {
                return json([
                    'code' => 0,
                    'msg' => '二级验证安全码错误！',
                    'data' => '',
                ]);
            }
        }
        $res = $DB->where('uid', $uid)->update(
            [
                'login_password' => password_hash($pwd, PASSWORD_DEFAULT),   //函数加密处理  解密方法 password_verify('匹配密码','数据库密码')
                'updated_at' => Carbon::now()->toDateTimeString()
            ]
        );
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    /**
     * @param Request $request
     * @param User $DB
     * @return \support\Response
     * 修改交易密码
     */
    public function changeTradePassword(Request $request, User $DB)
    {
        $pwd = $request->post('trade_password');
        // 获取当前用户ID
        $uid = $request->uid;
        //二级安全码
        $id_auth = $DB->where('uid', $uid)->value('is_auth');
        if ($id_auth == 1) {
            $auth_password = $request->post('auth_password');
            $auth_password_db = $DB->where('uid', $uid)->value('auth_password');
            if (!$this->verifyTradePwd($auth_password, $auth_password_db)) {
                return json([
                    'code' => 0,
                    'msg' => '二级验证安全码错误！',
                    'data' => '',
                ]);
            }
        }
        $res = $DB->where('uid', $uid)->update(
            [
                'trade_password' => password_hash($pwd, PASSWORD_DEFAULT),   //函数加密处理  解密方法 password_verify('匹配密码','数据库密码')
                'updated_at' => Carbon::now()->toDateTimeString()
            ]
        );
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    /**
     * @param Request $request
     * @param User $DB
     * @return \support\Response
     * 修改二级安全码
     */
    public function changeAuthPassword(Request $request, User $DB)
    {
        $pwd = $request->post('auth_password');
        // 获取当前用户ID
        $uid = $request->uid;
        $res = $DB->where('uid', $uid)->update(
            [
                'auth_password' => password_hash($pwd, PASSWORD_DEFAULT),   //函数加密处理  解密方法 password_verify('匹配密码','数据库密码')
                'updated_at' => Carbon::now()->toDateTimeString()
            ]
        );
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    public function lockAuthPassword(Request $request, User $DB)
    {
        // 获取当前用户ID
        $uid = $request->uid;
        $is_auth = $DB->where('uid', $uid)->value('is_auth');
        $res = $DB->where('uid', $uid)->update(
            [
                'is_auth' => $is_auth == 1 ? 0 : 1,
                'updated_at' => Carbon::now()->toDateTimeString()
            ]
        );
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    /***
     *
     * 修改用戶信息
     */
    public function updateUserInfo(Request $request, User $DB)
    {
        $nickname = $request->post('nickname');
        // 获取当前用户ID
        $uid = JwtToken::getCurrentId();
        $res = $DB->where('uid', $uid)->update(
            [
//                'avatar'=>$avatar,
                'nickname' => $nickname,
                'updated_at' => Carbon::now()->toDateTimeString()
            ]
        );
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }


}
